package com.htzos.base.parent.ctrl;

import java.io.File;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.htzos.common.util.PropertiesUtil;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController implements Serializable{
	/**
	 * 序列号ID
	 */
	private static final long serialVersionUID = -5575691396185442020L;

	@RequestMapping("/fileupload")
	public void fileuplaod(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		//创建文件夹
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMM");
		String yymm = sdf.format(new Date());

		//*/
		//path
		String path = PropertiesUtil.WORKNAME;
		String rpath =PropertiesUtil.UPLOADFOLDER+"/"+path+"/"+yymm+"/";
		String fileroot=PropertiesUtil.DATA_PATH+rpath;
		File file =new File(fileroot);  
		//如果文件夹不存在则创建  
		if  (!file.exists()&& !file.isDirectory()){     
		    file.mkdirs();  
		}
		// 获得磁盘文件条目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 高水平的API文件上传处理
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			// 提交上来的信息都在这个list里面
			// 这意味着可以上传多个文件
			List<FileItem> list = upload.parseRequest(request);
			// 获取上传的文件
			System.out.println(list);
			List<String> filelist = new ArrayList<String>();
			boolean multiple = false;
			for(FileItem item : list){
				
				//判断文件大小
				long size=item.getSize();
				if(size>PropertiesUtil.UPLOADMAXSIZE){
					filelist.add("您上传的文件太大了 ，我们服务器暂时干不动！");//PATH_FOLDER+
					break;
				}
				
				if(item.isFormField())
				{
					if(item.getFieldName().equals("multiple"))
						multiple = true;
					continue;
				}

				String fileName = getUploadFileName(item);
				
				if(PropertiesUtil.FILERENAME){
					// 获取文件名
					fileName = getUploadFileName(item);
				}else{
					fileName = getFileName(item);
				}

				System.out.println("存放目录:" + fileroot);
				System.out.println("文件名:" + fileName);
				// 真正写到磁盘上
				item.write(new File(fileroot, fileName));
				filelist.add(PropertiesUtil.BASE_URL+"/"+rpath+fileName);//PATH_FOLDER+
			}
			
			PrintWriter writer = response.getWriter();

			if(multiple) 
			{
				writer.print(JSONArray.fromObject(filelist));
			}
			else {
				writer.print(filelist.get(0));
			}
			writer.close();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String getUploadFileName(FileItem item) {
		// 获取路径名
		String value = item.getName();
		// 索引到最后一个反斜杠
		int start = value.lastIndexOf("\\");
		// 截取 上传文件的 字符串名字，加1是 去掉反斜杠，
		String filename = value.substring(start + 1);
		
		String rname = String.valueOf(System.currentTimeMillis()) + String.format("%02d", Math.round(Math.random()*100));//取得当前时间，Date()是java.util包里的，这作为真实名称
		int i = filename.lastIndexOf(".");//原名称里倒数第一个"."在哪里 
		String ext = filename.substring(i+1);//取得后缀，及"."后面的字符 
		filename = rname+"."+ext;
		
		return filename;
	}
	
	private String getFileName(FileItem item){
		// 获取路径名
		String value = item.getName();
		// 索引到最后一个反斜杠
		int start = value.lastIndexOf("\\");
		// 截取 上传文件的 字符串名字，加1是 去掉反斜杠，
		String filename = value.substring(start + 1);
		return filename;
	}
	
}
